<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
        <el-alert title="添加商品信息" type="info" center show-icon :closable='false'></el-alert>
        <el-steps :space="200" :active="activeIndex - 0" finish-status="success" align-center>
          <el-step title="基本信息"></el-step>
          <el-step title="商品参数"></el-step>
          <el-step title="商品属性"></el-step>
          <el-step title="商品图片"></el-step>
          <el-step title="商品内容"></el-step>
          <el-step title="完成"></el-step>
        </el-steps>
        <el-form :model="addForm" :rules="addFormRules" ref="ref_addForm" label-position='top'>
          <el-tabs v-model='activeIndex' tab-position="left" :before-leave='beforeLeave' @tab-click='tabClick' >
            <el-tab-pane label="基本参数" name='0'>
              <el-form-item label='商品名称' prop='goods_name'>
                <el-input v-model='addForm.goods_name'></el-input>
              </el-form-item>
              <el-form-item label='商品价格' prop='goods_price'>
                <el-input v-model='addForm.goods_price' type='number'></el-input>
              </el-form-item>
              <el-form-item label='商品数量' prop='goods_number'>
                <el-input v-model='addForm.goods_number'  type='number'></el-input>
              </el-form-item>
              <el-form-item label='商品重量' prop='goods_weight'>
                <el-input v-model='addForm.goods_weight'  type='number'></el-input>
              </el-form-item>
              <el-form-item label='商品分类' prop='goods_cat'>
                <el-cascader
                  v-model="addForm.goods_cat"
                  :options="dataList"
                  :props="props"
                  @change="handleChange">
                </el-cascader>
              </el-form-item>
              
            </el-tab-pane>
            <el-tab-pane label="商品参数" name='1' >
              <el-form-item :label='i.attr_name' v-for='i in manyData' :key='i.attr_id' >
                <el-checkbox-group v-model="i.attr_vals" >
                  <el-checkbox class='checkbox' border :label="j" v-for='(j,k) in i.attr_vals' :key='k'></el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="商品属性" name='2'>
              <el-form-item :label='i.attr_name' v-for='i in onlyData' :key='i.attr_id'>
                <el-input v-model='i.attr_vals'></el-input>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="商品图片" name='3'>
              <el-upload
                class="upload-demo"
                action="http://127.0.0.1:8888/api/private/v1/upload"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :file-list="fileList"
                list-type="picture"
                :headers='token'
                @on-success='uploadsuccess'>
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
            </el-tab-pane>
            <el-tab-pane label="商品内容" name='4'>
              <quill-editor 
                v-model="addForm.goods_introduce">
              </quill-editor>
              <el-button style='margin-top:20px' type="primary" @click='add'>添加商品</el-button>
            </el-tab-pane>
          </el-tabs>
        </el-form>
    </el-card>
    <el-dialog
      title="图片预览"
      :visible.sync="dialogVisible"
      width="50%">
      <img :src="previewPath">
    </el-dialog>
    
  </div>
</template>

<script>
import _ from 'lodash' 
export default {
  data(){
    return {
      dialogVisible:false,
      props:{ 
        expandTrigger: 'hover' ,
        value:'cat_id',
        label:'cat_name',
        children:'children'
      },
      fileList:[],
      onlyData:[],
      manyData:[],
      token:{
       Authorization:window.sessionStorage.getItem('token')
      },
      previewPath:'',
      activeIndex:0,
      dataList:[],
      addForm:{
        goods_name:'',
        goods_price:0,
        goods_number:0,
        goods_weight:0,
        goods_cat:[],
        pics:[],
        goods_introduce:'',
        attrs:[],
      },
      addFormRules:{
        goods_name:[
          { required:true, message:'请输入商品名称', trigger:'blur'},
        ],
        goods_price:[
          { required:true, message:'请输入商品价格', trigger:'blur'},
        ],
        goods_number:[
          { required:true, message:'请输入商品数量', trigger:'blur'},
        ],
        goods_weight:[
          { required:true, message:'请输入商品重量', trigger:'blur'},
        ],
        goods_cat:[
          { required:true, message:'请选择商品', trigger:'blur'},
        ]
      },
    }
  },
  computed:{
    selectParenId(){
      if( this.addForm.goods_cat.length === 3 )
       return this.addForm.goods_cat[2]
      else return null
    }
  },
  methods:{
    async getData(){
      let res = await this.axios.get('/categories')
      if( res.data.meta.status == 200 ) {
        this.dataList = res.data.data
      } else {
        this.pop.error(res.data.meta.msg)
      }
    },
    handleChange(){
      if( this.addForm.goods_cat.length != 3 ) return this.addForm.goods_cat = []
    },
    beforeLeave(active, old){
      if( old === '0' && this.addForm.goods_cat.length !== 3) {
        this.pop.error('请选择商品分类')
        return false
      }
    },
    async tabClick(){
      if( this.activeIndex === '1' ) {
        let res = await this.axios.get(`categories/${ this.selectParenId }/attributes`, {
          params:{ sel:'many' }
        })
        if( res.data.meta.status == 200 ) {
          res.data.data.forEach( item => {
            if(item.attr_vals.length == 0) item.attr_vals = []
            else item.attr_vals = item.attr_vals.split(' ')
          })
          this.manyData = res.data.data
        } else {
          this.pop.error( res.data.meta.msg )
        }
      } else if( this.activeIndex === '2' ) {
        let res = await this.axios.get(`categories/${ this.selectParenId }/attributes`, {
          params:{ sel : 'only' }
        })
        if( res.data.meta.status == 200 ) {
          this.onlyData = res.data.data
        } else {
          this.pop.error(res.data.meta.msg)
        }
      }
    },
    handlePreview(file) {
      this.previewPath = file.response.data.url
      this.dialogVisible = true
    },
    handleRemove(file){
      let filepath = file.response.data.tmp_path
      let index = this.addForm.pics.findIndex( item=>item.pic === filepath)
      this.addForm.pics.splice(index, 1)
    },
    uploadsuccess(res) {
      let pic = { pic:res.data.tmp_path }
      this.addForm.pics.push(pic)
    },
    add(){
      this.$refs.ref_addForm.validate(async res => {
        if( !res ) return this.pop('请填写完整！！')
        let copy = _.cloneDeep(this.addForm)
        copy.goods_cat = copy.goods_cat.join(',')
        this.manyData.forEach( item => {
          let List = {
            attr_id: item.attr_id,
            attr_value:item.attr_vals.join(' ')
          }
          this.addForm.attrs.push(List)
        })
        this.onlyData.forEach( item => {
          let List = {
            attr_id: item.attr_id,
            attr_value:item.attr_vals
          }
          this.addForm.attrs.push(List)
        })
        copy.attrs = this.addForm.attrs
        res = await this.axios.post('/goods', copy)
        if( res.data.meta.status == 201 ){
          this.pop.success(res.data.meta.msg)
          this.$router.push('/goods')
        } else {
          this.pop.error(res.data.meta.msg)
        }
      })
    }
  },
  created(){
    this.getData()
  }
}
</script>

<style lang='scss' scoped>
.el-breadcrumb {
  padding:15px 0;
}
.el-steps {
  width:100%;
  display: flex;
  justify-content: center;
  margin:15px 0;
}
.el-step_title {
  font-size: 13px;
}
.checkbox {
  margin:0 5px 0 0 !important;
}
img {
  width:100%;
  height:100%;
}


</style>